<?php

namespace App\Http\Controllers\Entity\Asset\Vlive;

use App\Admin\Extensions\Tools\GridView;
use App\Classes\Injection\VchanInjection;
use App\Classes\Publish\Publication;
use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Asset\Vlive\VchanRequest;
use App\Jobs\Import\ImportVchanJob;
use App\Jobs\Injection\VchanInjectionJob;
use App\Jobs\Publish\VchanJob;
use App\Models\Common\CatData\Video\Vcareacat;
use App\Models\Common\CatData\Video\Vccat;
use App\Models\Common\CatData\Video\Vccattag;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Common\Enumdata\Enumop\Video\Vlang;
use App\Models\Entity\Asset\Vlive\Vchan;
use App\Models\Entity\Asset\Vlive\VchanVccattag;
use App\Models\Entity\Asset\Vlive\Vcposter;
use App\Models\Entity\Asset\Vlive\Vcstream;
use App\Models\Entity\Asset\Vlive\Vepg;
use App\Models\Import\BatchImportVchanHistory;
use App\Models\Injection\InjectVchanHistory;
use App\Repositories\Entity\Asset\Vlive\VchanRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Tab;
use Excel;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class VchanController extends Controller
{
    use ModelForm;

    /** @var  VchanRepository */
    private $vchanRepository;

    public function __construct(VchanRepository $vchanRepo)
    {
        $this->vchanRepository = $vchanRepo;
    }

    /**
     * Display a listing of the Vchan.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.asset.vlive.vchans.index_header'));
            $content->description(__('entity.asset.vlive.vchans.index_description'));

            $content->body($this->grid());
            // $content->row(view('entity.tag.addContentTagModal'));
        });
    }

    /**
     * Show the form for creating a new Vchan.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.asset.vlive.vchans.create_header'));
            $content->description(__('entity.asset.vlive.vchans.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Vchan in storage.
     *
     * @param VchanRequest $request
     *
     * @return Response
     */
    public function store(VchanRequest $request)
    {
        $input     = $request->all();
        $vcstreams = $request->get('vcstreams');
        if (!$vcstreams[0]) {
            Flash::error('直播频道流必须填写');
            return back()->withInput();
        }
        $image = $request->file('vlogo'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.vchan');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['backimg'] = $rootDir . $fullPath;

                $input['vlogo'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $vchan = $this->vchanRepository->create($input);

        if ($vchan) {
            if (is_array($request->get('sps'))) {
                $vchan->sps()->sync(array_filter($request->get('sps')));
            }
            if (is_array($request->get('vccattags'))) {
                $vchan->vccattags()->sync(array_filter($request->get('vccattags')));
            }
            if (is_array($request->get('vcareacats'))) {
                $vchan->vcareacats()->sync(array_filter($request->get('vcareacats')));
            }
            if (is_array($request->get('vlangs'))) {
                $vchan->vlangs()->sync(array_filter($request->get('vlangs')));
            }
            if (is_array($request->get('vcposters'))) {
                $vchan->vcposters()->sync(array_filter($request->get('vcposters')));
            }
            if (is_array($request->get('vcstreams'))) {
                $vchan->vcstreams()->sync(array_filter($request->get('vcstreams')));
            }
            if (is_array($request->get('vepgs'))) {
                $vchan->vepgs()->sync(array_filter($request->get('vepgs')));
            }
        }

        Flash::success(__('entity.asset.vlive.vchans.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.vlive.vchans.index'));

    }

    /**
     * Display the specified Vchan.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $vchan = $this->vchanRepository->findWithoutFail($id);

        if (empty($vchan)) {
            Flash::error(__('entity.asset.vlive.vchans.not_found'));

            return redirect(route('entity.asset.vlive.vchans.index'));
        }

        return view('entity.asset.vlive.vchans.show')->with('vchan', $vchan);

    }

    /**
     * Show the form for editing the specified Vchan.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.asset.vlive.vchans.edit_header'));
            $content->description(__('entity.asset.vlive.vchans.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Vchan in storage.
     *
     * @param  int              $id
     * @param VchanRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {

        $vchan = $this->vchanRepository->findWithoutFail($id);

        if (empty($vchan)) {
            Flash::error(__('entity.asset.vlive.vchans.not_found'));

            return redirect(route('entity.asset.vlive.vchans.index'));
        }
        $vcstreams = $request->get('vcstreams');
        if (!$vcstreams[0]) {
            Flash::error('直播频道流必须填写');
            return back()->withInput();
        }

        $input = $request->all();

        if (array_key_exists('_file_del_', $input)) {

            $imgUrl       = $vchan->vlogo;
            $uploadConfig = config('custom.base.upload.vchan');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];

            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                // $album->backimg = null;
                // $album->save();
                return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
            }

            return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
        }

        $sValidators = [
            'vchan_no'    => 'required|max:100|unique:vchans,vchan_no,' . $id,
            'name'        => 'required',
            'charge_type' => 'required',
            'vccat_id'    => 'required',
            'title'       => 'required',
            'listorder'   => 'required',
        ];

        $validators = [];
        // 判断是否行内编辑,只有下线的可以编辑
        $status = Vchan::where(['online_status' => 0, 'id' => $id])->first();
        if ($status) {
            $input = $this->handleEditable($input);
        }

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'vchan_no'    => '编号',
            'name'        => '名称',
            'charge_type' => '收费类型',
            'title'       => '标题',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }

        $image = $request->file('vlogo'); // 使用laravel 自带的request类来获取一下文件
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径

                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;

                // 上传图片
                $uploadConfig = config('custom.base.upload.vchan');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['backimg'] = $rootDir . $fullPath;

                $input['vlogo'] = $fullPath;

                // 2017/08/22 modify
                // 删除原先存储的图片
                $flag = Storage::disk($driver)->delete($vchan->vlogo);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $vchan = $this->vchanRepository->update($input, $id);

        if ($vchan) {
            if (is_array($request->get('sps'))) {
                $vchan->sps()->sync(array_filter($request->get('sps')));
            }
            if (is_array($request->get('vccattags'))) {
                $vchan->vccattags()->sync(array_filter($request->get('vccattags')));
            }
            if (is_array($request->get('vcareacats'))) {
                $vchan->vcareacats()->sync(array_filter($request->get('vcareacats')));
            }
            if (is_array($request->get('vlangs'))) {
                $vchan->vlangs()->sync(array_filter($request->get('vlangs')));
            }
            if (is_array($request->get('vcposters'))) {
                $vchan->vcposters()->sync(array_filter($request->get('vcposters')));
            }
            if (is_array($request->get('vcstreams'))) {
                $vchan->vcstreams()->sync(array_filter($request->get('vcstreams')));
            }
            if (is_array($request->get('vepgs'))) {
                $vchan->vepgs()->sync(array_filter($request->get('vepgs')));
            }
        }

        Flash::success(__('entity.asset.vlive.vchans.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.vlive.vchans.index'));
    }

    /**
     * Remove the specified Vchan from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->vchanRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('entity.asset.vlive.vchans.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $vchan = $this->vchanRepository->findWithoutFail($id);

        if (empty($vchan)) {
            Flash::error(__('entity.asset.vlive.vchans.not_found'));

            return redirect(route('entity.asset.vlive.vchans.index'));
        }

        if ($flag = $this->vchanRepository->delete($id)) {

            $vchan->sps()->detach();
            $vchan->vccattags()->detach();
            $vchan->vcareacats()->detach();
            $vchan->vlangs()->detach();
            $vchan->vcposters()->detach();
            $vchan->vcstreams()->detach();
            $vchan->vepgs()->detach();
            return response()->json(['message' => __('entity.asset.vlive.vchans.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * 直播媒资详情
     */

    public function vchanDetails($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('直播媒资详情'));

            // if (Request::get('view') !== 'table') {
            //     $grid->view('admin.grid.card');
            // }

            // 剧集详情
            $data = $this->vchanDetailsData($id);
            $content->row(view('entity.asset.vlive.vchan.details', $data));

            // 剧集详情
            // $content->row($this->assetDetailsBox($id));

            // 分集数据
            $content->row($this->vchanTab($id));
            // $content->body($this->vassetiGrid($id));
        });
    }

    /**
     * 直播详情的数据
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function vchanDetailsData($id)
    {
        $vchanDetails = Vchan::where('id', '=', $id)->with('sps', 'vlangs', 'vcareacats', 'vccattags', 'vccat')->first();

        // 服务商
        $sps = '';
        if ($sps = $vchanDetails->sps) {
            $sps = $vchanDetails->sps->pluck('name')->implode(',');
        }
        // 语言
        $vlangs = '';
        if ($vlangs = $vchanDetails->vlangs) {
            $vlangs = $vchanDetails->vlangs->pluck('name')->implode(',');
        }
        // 地区
        $vcareacats = '';
        if ($vcareacats = $vchanDetails->vcareacats) {
            $vcareacats = $vchanDetails->vcareacats->pluck('name')->implode(',');
        }
        // 归类
        $vccat = '';
        if ($vccat = $vchanDetails->vccat) {
            $vccat = $vchanDetails->vccat->name;
        }
        // 分类
        $vccattags = '';
        if ($vccattags = $vchanDetails->vccattags) {
            $vccattags = $vchanDetails->vccattags->pluck('name')->implode(',');
        }

        $data['name']        = $vchanDetails->name;
        $data['vchan_no']    = $vchanDetails->vchan_no;
        $data['title']       = $vchanDetails->title;
        $data['subtitle']    = $vchanDetails->subtitle;
        $data['vccattags']   = $vccattags;
        $data['vccat']       = $vccat;
        $data['short_desc']  = $vchanDetails->short_desc;
        $data['long_desc']   = $vchanDetails->long_desc;
        $data['sps']         = $sps;
        $data['vlangs']      = $vlangs;
        $data['vcareacats']  = $vcareacats;
        $data['expiring_at'] = date('Y-m-d', strtotime($vchanDetails->expiring_at)); // $vchanDetails->firstdate
        $data['online_at']   = date('Y-m-d', strtotime($vchanDetails->online_at)); // $vchanDetails->online_at
        $data['offline_at']  = date('Y-m-d', strtotime($vchanDetails->offline_at)); // $vchanDetails->offline_at;

        return $data;
    }

    /**
     * 直播相关tab
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function vchanTab($id)
    {
        $tab = new Tab();
        $tab->add('直播频道流', $this->vcstreamGrid($id));
        $tab->add('直播海报', $this->vcposterGrid($id));
        $tab->add('epg源', $this->vepgGrid($id));
        return $tab;
    }

    /**
     * 直播频道流信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function vcstreamGrid($id)
    {

        return Admin::grid(Vcstream::class, function (Grid $grid) use ($id) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 添加按钮
            if (Admin::user()->cannot('entity.asset.vlive.vcstreams.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.vlive.vcstreams.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.asset.vlive.vcstreams.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.asset.vlive.vcstreams.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.asset.vlive.vcstreams.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $vcstreams = Vchan::find($id)->vcstreams->toArray();
            $grid->model()->whereIn('id', array_column($vcstreams, 'id'));
            $grid->column('cstream_no', '编号')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('short_sesc', '简述')->sortable();
            $grid->column('long_desc', '详述')->sortable();
            $grid->column('duration', '流时长')->sortable();
            $grid->column('type', '流类型')->sortable();
            $grid->column('vcodec', '流视频编码')->sortable();
            $grid->column('acodec', '流音频编码')->sortable();
            $grid->column('bitrate', '流码率')->sortable();
            $grid->column('timeshift', '是否支持时移')->display(function ($val){
                if ($val == 1) {
                    return '<span class="badge bg-green">是</span>';
                } else {
                    return '<span class="badge bg-red">否</span>';
                }
            })->sortable();
            $grid->column('created_at', '创建日期')->sortable();
            $grid->column('updated_at', '更新日期')->sortable();
            $grid->column('vchan.name', '所属直播')->sortable();

            $grid->resource(route('entity.asset.vlive.vcstreams.vchan.index', ['vchan_id' => $id]));
            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();

            });
        });
    }

    /**
     * 直播海报信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function vcposterGrid($id)
    {

        return Admin::grid(Vcposter::class, function (Grid $grid) use ($id) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            $uploadConfig = config('custom.base.upload.vchan');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];

            // 添加按钮
            if (Admin::user()->cannot('entity.asset.vlive.vcposters.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.vlive.vcposters.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.asset.vlive.vcposters.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.asset.vlive.vcposters.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.asset.vlive.vcposters.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $vcposters = Vchan::find($id)->vcposters->toArray();
            $grid->model()->whereIn('id', array_column($vcposters, 'id'));
            $grid->column('vcposter_no', '编号')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('short_desc', '简述')->sortable();
            $grid->column('long_desc', '详述')->sortable();
            $grid->column('cposter_url', '海报路径')->sortable();
            $grid->column('specification', '海报规格类型')->sortable();
            $grid->column('dimension', '海报尺寸比例')->sortable();
            $grid->column('created_at', '创建日期')->sortable();
            $grid->column('updated_at', '更新日期')->sortable();
            
            $grid->resource(route('entity.asset.vlive.vcposters.vchan.index', ['vchan_id' => $id]));

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();

            });

            // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
            $data = Vchan::where('id', '=', $id)->select('online_status', 'publish_status')->first();

            if ($data && $data->online_status == 1 && $data->publish_status == 1) {
                // 禁用行操作列
                $grid->disableActions();
                // 禁用创建按钮
                $grid->disableCreation();

                $flag = false;

            } else {

                $flag = true;

            }

            $grid->tools(function ($tools) {
                $tools->append(new GridView());
            });
            if (\Illuminate\Support\Facades\Request::get('view') !== 'table') {
                $grid->setView('admin.grid.card', ['image_column' => 'cposter_url', 'text_column' => 'title', 'server' => $host, 'flag' => $flag]);
            }
        }, 'vcposter');

        // });
    }

    /**
     * epg源信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function vepgGrid($id)
    {

        return Admin::grid(Vepg::class, function (Grid $grid) use ($id) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 添加按钮
            if (Admin::user()->cannot('entity.asset.vlive.vepgs.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.vlive.vepgs.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.asset.vlive.vepgs.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.asset.vlive.vepgs.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.asset.vlive.vepgs.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $vepgs = Vchan::find($id)->vepgs->toArray();
            $grid->model()->whereIn('id', array_column($vepgs, 'id'));
            $grid->column('vepg_no', '编号')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('epg_url', 'EPG路径')->sortable();
            $grid->column('epgFormat.name', 'EPG格式')->sortable();
            $grid->column('short_desc', '简述')->sortable();
            $grid->column('long_desc', '详述')->sortable();
            $grid->column('start_time', '节目开始时间')->sortable();
            $grid->column('end_time', '节目结束时间')->sortable();
            $grid->column('created_at', '创建日期')->sortable();
            $grid->column('updated_at', '更新日期')->sortable();
            $grid->resource(route('entity.asset.vlive.vepgs.vchan.index', ['vchan_id' => $id]));

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();

            });
        });
    }

    /**
     * 批量导入媒资-视图
     * @param Request $request
     */
    public function batchImportView()
    {
        return Admin::content(function (Content $content) {
            $content->header(__('entity.asset.vlive.vchans.batch_import_header'));
            $content->description(__('entity.asset.vlive.vchans.batch_import_description'));

            $box = new Box('模板说明', '<p><b>编号</b>(必填), <b>CP/SP</b>(必填), <b>名称</b>(必填), <b>分类</b>(非必填, 多个分类之间使用<b>&</b>连接), <b>归类</b>(必填), <b>语言</b>(非必填, 多个分类之间使用<b>&</b>连接), <b>时长(分钟)</b>(非必填, 整数, 默认给60), <b>地区</b>(必填, 多个地区之间使用<b>&</b>连接),<b>简介</b>(必填), <b>详情</b>(非必填), <b>台标地址</b>(非必填), <b>直播源地址</b>(非必填), <b>海报文件目录</b>(非必填), <b>EPG文件目录</b>(非必填)。点击 "下载模板" 按钮, 进行数据格式的下载!<a href="/upload/batch_import_template/vchan_sample.xlsx" class="btn btn-warning" target="_blank"><i class="fa fa-download"></i>下载模板</a></p></p>');
            $content->row($box->style('primary'));

            $content->body($this->batchImportForm());
        });
    }

    /**
     * 批量的导入媒资的form
     */
    protected function batchImportForm()
    {
        // Admin::script('tian();');

        // 文件
        return Admin::form(Vchan::class, function (Form $form) {
            // 设置表单提交的action
            $form->setAction(route('entity.asset.vlive.vchan.batch_import'));
            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                // $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                // $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
            });

            Admin::script('batchImportVchan();');

            $form->file('file', '文件');
        });
    }

    /**
     * 批量导入媒资
     */
    public function batchImport(Request $request)
    {
        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            'file' => 'required', // |mimes:xls,csv,xlsx
        ], [
            'required' => ':attribute 未上传',
            // 'mimes' => '文件格式只能为 :attribute',
        ], [
            'file' => '文件',
        ]);
        // 校验
        if ($validator->fails()) {
            // json返回
            return response()->json(['status' => 'error', 'content' => '文件不能为空!']);

            // return back()->withErrors($validator)->withInput();
        }

        // 上传文件:
        $file = $request->file('file');
        if ($file->isValid()) {
            // 允许上传的文件格式
            $allowed_extensions = ["xls", "xlsx", "csv"];
            // 上传文件的后缀, 扩展名
            $entension = $file->getClientOriginalExtension();
            if ($entension && !in_array($entension, $allowed_extensions)) {
                // json返回
                return response()->json(['status' => 'error', 'content' => '文件格式只能为xls, xlsx, csv!']);

                // Flash::error('文件格式只能为xls, xlsx, csv!');
                // // 关联持久用户提交的信息
                // return back()->withInput();
            }
            //获取文件尺寸
            $size = $file->getSize();
            // 文件最大限制, 现在是10M
            $file_max_size = config('custom.base.file_max_size');
            // $size = round($file->getSize() / 1024 / 1024);
            if ($size > $file_max_size) {
                // json返回
                return response()->json(['status' => 'error', 'content' => '文件最大只能10M!']);

                // Flash::error('文件最大只能10M!');
                // return back()->withInput(); //关联持久用户提交的信息
            }

            $originalName = $file->getClientOriginalName(); // 文件原名
            $type         = $file->getClientMimeType(); // image/jpeg
            $realPath     = $file->getRealPath(); // 临时文件的绝对路径
            $fileName     = date('YmdHis') . '-' . uniqid();
            $newName      = $fileName . '.' . $entension;
            // 文件上传的根路径
            $rootDir     = config('filesystems.disks.custom.root');
            $path        = $file->move($rootDir . '/import_vchan', $newName);
            $cretae_path = $rootDir . '/import_vchan/' . $newName;
            // 保存日志时文件路径
            $file_url = '/import_vchan/' . $newName;

            // 通过excel先读取一下总行数, 效率有点低, 因为先将所有的excel数据读入到内存了
            $count = 0;
            Excel::load($cretae_path, function ($reader) use (&$count) {
                $reader = $reader->getSheet(0);
                //获取表中的数据
                $data  = $reader->toArray();
                $num   = count($data);
                $count = $num - 1;
            });
            // 创建一条记录
            $batchImportVchanHistory                 = new BatchImportVchanHistory;
            $batchImportVchanHistory->batch_no       = date('YmdHis');
            $batchImportVchanHistory->task_no        = date('YmdHis') . uniqid();
            $batchImportVchanHistory->done_count     = 0;
            $batchImportVchanHistory->file_url       = $file_url;
            $batchImportVchanHistory->success_count  = 0;
            $batchImportVchanHistory->error_count    = 0;
            $batchImportVchanHistory->count          = $count;
            $batchImportVchanHistory->content        = "开始";
            $batchImportVchanHistory->consuming_time = 0;
            $batchImportVchanHistory->used_memory    = 0;
            $batchImportVchanHistory->user_id        = Admin::user()->id;
            $batchImportVchanHistory->save();
            // 触发队列
            dispatch(new ImportVchanJob($cretae_path, $batchImportVchanHistory));

            // json返回
            return response()->json(['status' => 'success', 'content' => $batchImportVchanHistory->task_no]);

            // return back()->withInput();
        } else {
            // json返回
            return response()->json(['status' => 'error', 'content' => '文件上传失败!']);

            // Flash::error('文件上传失败');
            // return back()->withInput(); //关联持久用户提交的信息
        }
    }

    /**
     * 批量导入媒资进度
     * [queryProgress description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function bacthImportProgress(Request $request)
    {
        $taskNo = $request->input('task_no');
        $data   = BatchImportVchanHistory::where('task_no', $taskNo)->first();
        // 记录数为0[异常]
        if ($data->count === 0) {
            return response()->json(['content' => '记录数为0!', 'status' => 'success']);
        }
        // 完成数为0
        if ($data->done_count === 0) {
            return response()->json(['content' => '0%', 'status' => 'progress']);
        }
        // 完成的时候
        if ($data->count === $data->done_count) {
            return response()->json(['content' => $data->content, 'status' => 'success']);
        }
        // 异常
        if ($data->count < $data->done_count) {
            return response()->json(['content' => '任务异常, 完成数大于总数！', 'status' => 'success']);
        }
        return response()->json(['content' => ceil($data->done_count * 100 / $data->count) . '%', 'status' => 'progress']);
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.asset.vlive.vchans.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vasseti::where(['online_status' => 0, 'publish_down_status' => 1])->count();
        $result = Publication::getTotalNum(new Vchan(), [
            [['online_status' => 0], 'ID为以下媒资已经上线: '],
            [['publish_down_status' => 1], 'ID为以下媒资还未下线发布: '],
        ], '媒资上线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '剧集上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new VchanJob(['dispatch', 'up'], '', $taskid));
        $content = $content ? $content : '上线成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.asset.vlive.vchans.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vasseti::where(['online_status' => 1])->count();
        $result = Publication::getTotalNum(new Vchan(), [
            [['online_status' => 1], 'ID为以下媒资还没上线'],
        ], '媒资下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '剧集下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new VchanJob(['dispatch', 'down'], '', $taskid));
        $content = $content ? $content : '下线成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.asset.vlive.vchans.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vasseti::where(['online_status' => 1, 'publish_status' => 0, 'async_result' => 1])->count();
        $result = Publication::getTotalNum(new Vchan(), [
            [['online_status' => 1], 'ID为以下媒资还未上线: '],
            [['publish_status' => 0], 'ID为以下媒资已经上线发布: '],
            // [['async_result' => 1], 'ID为以下媒资还未注入: '],
        ], '媒资发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '剧集发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new VchanJob(['dispatch', 'publish'], '', $taskid));
        $content = $content ? $content : '发布成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.asset.vlive.vchans.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vasseti::where(['online_status' => 0, 'publish_down_status' => 0])->count();
        $result = Publication::getTotalNum(new Vchan(), [
            [['online_status' => 0], 'ID为以下媒资还未下线: '],
            [['publish_down_status' => 0], 'ID为以下媒资已经下线发布: '],
        ], '媒资下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '剧集下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new VchanJob(['dispatch', 'publishDown'], '', $taskid));
        $content = $content ? $content : '下线发布成功!';
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('entity.asset.vlive.vchans.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // 过滤ids
                $result = Publication::myfilter(new Vchan(), $request->ids, [
                    [['online_status' => 0], 'ID为以下媒资已经上线: '],
                    [['publish_down_status' => 1], 'ID为以下媒资还未下线发布: '],
                ], '媒资上线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Vchan(), $ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                // 如果所有的ids都能上线,显示上线操作成功,否则显示失败的ids
                $content = $content ? $content : '上线成功!';
                // 判断数据库状态是否更新成功
                $content = $result ? $content : '上线失败';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('entity.asset.vlive.vchans.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vchan(), $request->ids, [
                    [['online_status' => 1], 'ID为以下媒资还未上线: '],
                    [['publish_status' => 0], 'ID为以下媒资已经上线发布: '],
                    // [['async_result' => 1], 'ID为以下媒资还未注入: '],
                ], '媒资发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    $data   = ['task_type' => '直播媒资发布', 'user_id' => $user_id, 'total_num' => count($ids)];
                    $taskid = Publication::insertTasks($data);
                    dispatch(new VchanJob(['publish'], $ids, $taskid));
                    $url = route('entity.asset.vlive.vchans.progress');
                    return response()->json(['status' => 'success', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $vchans = Vchan::with(['vcposters', 'vccattags', 'vcstreams', 'vepgs'])
                    ->whereIn('id', $ids)->get();
                $vchans_vccattags     = VchanVccattag::whereIn('vchan_id', $ids)->get();
                $vchan_datas          = VchanJob::makeVchans($vchans);
                $vchan_vccattag_datas = VchanJob::makeVchanVccattags($vchans_vccattags);
                $result1              = Publication::insertApi('vchans', $vchan_datas);
                $result2              = Publication::insertApi('vchan_vccattags', $vchan_vccattag_datas);
                $result3              = Publication::updateMany(new Vchan(), $ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                // 如果所有的ids都能上线,显示上线操作成功,否则显示失败的ids
                $content = $content ? $content : '上线发布成功!';
                // 判断数据库状态是否更新成功
                $content = ($result1 && $result2 && $result3) ? $content : '上线发布失败';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('entity.asset.vlive.vchans.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vchan(), $request->ids, [
                    [[['async_result', '<>', 0]], 'ID为以下媒资正在注入'],
                    [['online_status' => 1], 'ID为以下媒资还没上线'],
                ], '媒资下线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Vchan(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                // 如果所有的ids都能上线,显示上线操作成功,否则显示失败的ids
                $content = $content ? $content : '下线成功!';
                // 判断数据库状态是否更新成功
                $content = $result ? $content : '下线失败';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('entity.asset.vlive.vchans.publish_one')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vchan(), $request->ids, [
                    [['online_status' => 0], 'ID为以下媒资还未下线: '],
                    [['publish_down_status' => 0], 'ID为以下媒资已经下线发布: '],
                ], '媒资下线发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 删除接口库中对应的数据
                $result1 = Publication::deleteApi('vchans', 'vchan_id', $ids);
                $result2 = Publication::deleteApi('vchan_vccattags', 'vchan_id', $ids);
                // 更新状态
                $result3 = Publication::updateMany(new Vchan(), $ids, [
                    'publish_down_status' => 1,
                    'user_id'             => $user_id,
                ]);
                // 如果所有的ids,显示操作成功,否则显示失败的ids
                $content = $content ? $content : '下线发布成功!';
                // 判断数据库状态是否更新成功
                $content = $result1 && $result2 && $result3 ? $content : '下线发布失败';
                return response()->json(['status' => 'success', 'content' => $content]);
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        return Publication::progress($taskid);
    }

    /**
     * 媒资注入[电视剧主集和电影]
     * [injection 媒资注入]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function injection(Request $request)
    {
        // 判断有没有数据需要发布[上线的媒资]
        if ($count = Vchan::where(['online_status' => 1])->count()) {
            // 创建一条记录
            $injectVchanHistory                 = new InjectVchanHistory;
            $injectVchanHistory->batch_no       = date('YmdHis');
            $injectVchanHistory->task_no        = date('YmdHis') . uniqid();
            $injectVchanHistory->done_count     = 0;
            $injectVchanHistory->count          = $count;
            $injectVchanHistory->content        = "开始";
            $injectVchanHistory->consuming_time = 0;
            $injectVchanHistory->used_memory    = 0;
            // $injectVchanHistory->user_id = $request->user()->id;
            $injectVchanHistory->save();

            // 触发队列
            dispatch(new VchanInjectionJob($injectVchanHistory));

            // json返回
            return response()->json(['status' => 'success', 'content' => $injectVchanHistory->task_no]);
        } else {
            return response()->json(['status' => 'error', 'content' => '没有需要注入的剧集, 判断剧集是否上线!']);
        }
    }

    /**
     * 媒资注入进度[直播]
     * [injectionProgress 媒资注入进度]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function injectionProgress(Request $request)
    {
        $taskNo = $request->input('task_no');
        $data   = InjectVchanHistory::where('task_no', $taskNo)->first();
        if ($data) {
            // 记录数为0[异常]
            if ($data->count === 0) {
                return response()->json(['content' => '记录数为0!', 'status' => 'success']);
            }
            // 完成数为0
            if ($data->done_count === 0) {
                return response()->json(['content' => '0%', 'status' => 'progress']);
            }
            // 完成的时候
            if ($data->count === $data->done_count) {
                return response()->json(['content' => $data->content, 'status' => 'success']);
            }
            // 异常
            if ($data->count < $data->done_count) {
                return response()->json(['content' => '任务异常, 完成数大于总数！', 'status' => 'success']);
            }
            return response()->json(['content' => ceil($data->done_count * 100 / $data->count) . '%', 'status' => 'progress']);
        } else {
            return response()->json(['content' => "非法任务号, 找不到该任务号的任务!", 'status' => 'success']);
        }
    }

    /**
     * 单个或多个媒资注入功能
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function injectOneOrMore(Request $request)
    {
        $ids = $request->input('ids');

        if (is_array($ids)) {
            // $count = Vasseti::where('online_status', '=', 1)->where('async_result', '!=', 0)->whereIn('id', $ids)->count();
            $count = Vchan::where('online_status', '=', 1)->whereIn('id', $ids)->count();
        } else {
            // $count = Vasseti::where('online_status', '=', 1)->where('async_result', '!=', 0)->where('id', $ids)->count();
            $count = Vchan::where('online_status', '=', 1)->where('id', $ids)->count();
        }
        // if (is_array($ids)) {
        //     $count = Vasseti::where('online_status', '=', 1)->whereIn('id', $ids)->count();
        // } else {
        //     $count = Vasseti::where('online_status', '=', 1)->where('id', $ids)->count();
        // }
        if ($count) {
            // 创建一条记录
            $injectVchanHistory                 = new InjectVchanHistory;
            $injectVchanHistory->batch_no       = date('YmdHis');
            $injectVchanHistory->task_no        = date('YmdHis') . uniqid();
            $injectVchanHistory->done_count     = 0;
            $injectVchanHistory->count          = $count;
            $injectVchanHistory->content        = "开始";
            $injectVchanHistory->consuming_time = 0;
            $injectVchanHistory->used_memory    = 0;
            // $injectVchanHistory->user_id = $request->user()->id;
            $injectVchanHistory->save();
            $vchanInjection = new VchanInjection($injectVchanHistory, $ids);
            $content        = $vchanInjection->handle();
            return response()->json(['status' => 'success', 'content' => $content]);
        } else {
            // return response()->json(['status' => 'error', 'content' => '该剧集还没上线或不存在']);
            return response()->json(['status' => 'error', 'content' => '该剧集还没上线,或不存在,或正在注入']);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Vchan::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('vchan_no', '直播编号');
            $form->text('name', '名称');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->image('vlogo', '台标')->removable();
            $form->text('short_desc', '简述');
            $form->text('long_desc', '详述');
            $form->radio('charge_type', '收费类型')->options(array(
                0 => '免费',
                1 => '收费',
            ))->default(1);
            $form->datetime('start_at', '开始日期');
            $form->datetime('expiring_at', '失效日期');
            $sps = Sp::pluck('name', 'id');
            $form->multipleSelect('sps', '服务商(SP)')->options($sps);
            $vccats = Vccat::pluck('name', 'id');
            $form->select('vccat_id', '归类')->options($vccats)->load('vccattags', route('common.cat_data.video.vccats.vccattag_or_empty'), 'id', 'name');
            $vccattags = Vccattag::pluck('name', 'id')->toArray();
            $form->multipleSelect('vccattags', '分类')->options($vccattags);
            $vcareacats = Vcareacat::pluck('name', 'id');
            $form->multipleSelect('vcareacats', '地区')->options($vcareacats);
            $vlangs = Vlang::pluck('name', 'id');
            $form->multipleSelect('vlangs', '语言')->options($vlangs);
            $vcposters = Vcposter::pluck('name', 'id');
            $form->multipleSelect('vcposters', '直播海报')->options($vcposters);
            $vcstreams = Vcstream::pluck('name', 'id');
            $form->multipleSelect('vcstreams', '直播频道流')->options($vcstreams);
            $vepgs = Vepg::pluck('name', 'id');
            $form->multipleSelect('vepgs', '直播频道EPG')->options($vepgs);
            $form->number('listorder', '排序');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Vchan::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('entity.asset.vlive.vchans.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('entity.asset.vlive.vchans.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('entity.asset.vlive.vchans.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('entity.asset.vlive.vchans.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('entity.asset.vlive.vchans.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('entity.asset.vlive.vchans.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $publish_status      = $actions->row->publish_status;
                $publish_down_status = $actions->row->publish_down_status;
                $async_result        = $actions->row->async_result;
                $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();

                $url = route('entity.asset.vlive.vchan_details', ['vchan_id' => $id]);
                $actions->prepend('<a href ="' . $url . '" title="直播媒资详情"><i class="fa fa-list"></i></a>');
                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.asset.vlive.vchans.up')) {
                    $url      = route('entity.asset.vlive.vchans.up');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 下线按钮
                if ($online_status === 1 && Admin::user()->can('entity.asset.vlive.vchans.down')) {
                    $url      = route('entity.asset.vlive.vchans.down');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }
                // 上线发布按钮
                if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('entity.asset.vlive.vchans.publish_one')) {
                    $url      = route('entity.asset.vlive.vchans.publish_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                }
                // 下线发布按钮
                if ($online_status === 0 && $publish_down_status === 0 && Admin::user()->can('entity.asset.vlive.vchans.publish_down_one')) {
                    $url      = route('entity.asset.vlive.vchans.publish_down_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                }
                // 媒资注入按钮
                if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('entity.asset.vlive.vchans.inject_one_or_more')) {
                    $function = "injectVchanOneOrMore({ids: $id})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="媒资注入"><i class="fa fa-filter"></i></a>');
                }
                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.vlive.vchans.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.asset.vlive.vchans.destroy')) {
                    $actions->disableDelete();
                }
                // 只有状态下线的资源才可以编辑
                if ($publish_down_status === 0) {
                    
                    $actions->disableEdit();
                    // $actions->disableDelete();
                }
                // 上线发布后不能删除
                if ($publish_status === 1) {
                    $actions->disableDelete();
                }
                //打标签
                $url = route('entity.tag.selectTag', ['tag_content_id' => $id,'tag_content_type'=>'vchan']);
                $actions->append('<a href="'.$url.'" data-toggle="modal"  data-target="#add-content-tag-modal" title="打标签"><i class="fa fa-paper-plane"></i></a>');

            });

            // 导出按钮
            if (Admin::user()->cannot('entity.asset.vlive.vchans.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                // 批量导入
                if (Admin::user()->can('entity.asset.vlive.vchan.batch_import_view')) {
                    $tools->append('<a href="' . route('entity.asset.vlive.vchan.batch_import_view') . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"><i class="fa fa-bars"></i>批量导入</a>');
                }
                // 媒资注入
                if (Admin::user()->can('entity.asset.vlive.vchan.injection')) {
                    $tools->append('<a href="javascript:void(0)" class="btn btn-sm btn-primary pull-right" style="margin-right: 10px" id="btn-vchans-injection"> <i class="fa fa-file-video-o"></i>媒资注入</a>');
                }
                $url2 = route('entity.asset.vlive.vchans.progress');
                // 下线发布功能
                if (Admin::user()->can('entity.asset.vlive.vchans.publish_down')) {
                    $url      = route('entity.asset.vlive.vchans.publish_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                }
                // 上线发布功能
                if (Admin::user()->can('entity.asset.vlive.vchans.publish')) {
                    $url      = route('entity.asset.vlive.vchans.publish');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                }
                // 全部下线功能
                if (Admin::user()->can('entity.asset.vlive.vchans.all_down')) {
                    $url      = route('entity.asset.vlive.vchans.all_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                }
                // 全部上线功能
                if (Admin::user()->can('entity.asset.vlive.vchans.all_up')) {
                    $url      = route('entity.asset.vlive.vchans.all_up');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                }
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.asset.vlive.vchans.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    if (Admin::user()->can('entity.asset.vlive.vchans.up')) {
                        $batch->add('上线', new \App\Admin\Extensions\Tools\Vchan\ReleaseVchan('up'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('entity.asset.vlive.vchans.down')) {
                        $batch->add('下线', new \App\Admin\Extensions\Tools\Vchan\ReleaseVchan('down'));
                    }
                    // 批量上线发布按钮
                    if (Admin::user()->can('entity.asset.vlive.vchans.publish_one')) {
                        $batch->add('上线发布', new \App\Admin\Extensions\Tools\Vchan\ReleaseVchan('publish'));
                    }
                    // 批量下线发布按钮
                    if (Admin::user()->can('entity.asset.vlive.vchans.publish_down_one')) {
                        $batch->add('下线发布', new \App\Admin\Extensions\Tools\Vchan\ReleaseVchan('publishDown'));
                    }
                    // 批量注入按钮
                    if (Admin::user()->can('entity.asset.vlive.vchans.inject_one_or_more')) {
                        $batch->add('媒资注入', new \App\Admin\Extensions\Tools\Vchan\BatchInjectVchan());
                    }

                    //批量打标签
                    // $batch->add('打标签', new \App\Admin\Extensions\Tools\contentTag('vchan'));
                });
            });
            
            $grid->column('id', 'ID')->sortable();
            $grid->column('vchan_no', '直播编号')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->editable();
            $uploadConfig = config('custom.base.upload.vchan');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('vlogo', '台标')->image($host);
            $grid->vcareacats('所属地区')->pluck('name')->label();
            $grid->vccattags('分类')->pluck('name')->label('info');
            // $grid->tags('标签')->pluck('name')->label('primary');
            $grid->vlangs('语言')->pluck('name')->label();
            $grid->column('charge_type', '收费类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-green">免费</span>';
                        break;

                    case 1:
                        return '<span class="badge bg-red">收费</span>';
                        break;
                }
            });
            $grid->column('start_at', '开始时间')->sortable();
            $grid->column('expiring_at', '失效时间')->sortable();
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('charge_type', '收费类型')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="label label-info">免费</span>';
                        break;

                    case 1:
                        return '<span class="label label-info">收费</span>';
                        break;
                }
            });
            $grid->column('async_result', '注入状态')->display(function ($val) {
                switch ($this->async_result) {
                    case 1:
                        return '<span class="badge bg-green">已注入</span>';
                        break;
                    case 0:
                        return '<span class="badge bg-yellow">正在注入</span>';
                        break;
                    default:
                        return '<span class="badge bg-red">未注入</span>';
                }
            })->sortable();
            $grid->column('short_desc', '简述')->sortable();
            $grid->column('listorder', '排序')->sortable();
            // $grid->sps('sps')->pluck('id')->label();
            // $grid->vccats('vccats')->pluck('id')->label();
            // $grid->vcareacats('vcareacats')->pluck('id')->label();
            // $grid->vlangs('vlangs')->pluck('id')->label();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                // 服务商(SP)
                $tempSps = Sp::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('sps', function ($query) use ($input) {
                        $query->where('sp_id', '=', "{$input}");
                    });

                }, '服务商')->select($tempSps);
                // 分类
                $tempVccats = Vccat::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vccats', function ($query) use ($input) {
                        $query->where('vccat_id', 'like', "{$input}");
                    });
                }, '分类')->select($tempVccats);
                // 编号
                $filter->like('vchan_no', '编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 拼音
                $filter->like('spell', '拼音');
                // 地区
                $tempVcareacats = Vcareacat::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vcareacats', function ($query) use ($input) {
                        $query->where('vcareacat_id', '=', "{$input}");
                    });
                }, '地区')->select($tempVcareacats);
                // 语言
                $tempVlangs = Vlang::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('vlangs', function ($query) use ($input) {
                        $query->where('vlang_id', '=', "{$input}");
                    });
                }, '语言')->select($tempVlangs);
                // 创建时间
                $filter->between('created_at', '创建时间')->datetime();
                // 更新时间
                $filter->between('updated_at', '更新时间')->datetime();
                // 上线时间
                $filter->between('online_at', '上线时间')->datetime();
                // 下线时间
                $filter->between('offline_at', '下线时间')->datetime();
                // 发布时间
                $filter->between('published_at', '发布时间')->datetime();
                // 注入状态
                // $filter->equal('async_result', '注入状态')->select(array(-1 => '未注入', 0 => '正在注入', 1 => '已注入'));
                // 是否收费
                // $filter->equal('charge_type', '注入状态')->select(array(0 => '免费', 1 => '收费'));
            });
        });
    }
}
